import {Button, List, Modal, Toast} from "antd-mobile";
import {AddSquareOutline} from "antd-mobile-icons";
import TitleNav from "../../utils/TitleNav";
import PassengerItem from "../../utils/PassengerItem";
import AddPassengerModal from "./component/AddPassengerModal";
import {useEffect, useState} from "react";
import {fetchPassengers, rmPassenger} from "../../utils/http/PassengerController";


const PassengersPage = () => {

    const [visible, setVisible] = useState(false);
    const [items, setItems] = useState<any>(null);

    const renderPassengers = () => {
        fetchPassengers()
            .then(res=>{
                const items = res.map((value: any)=>{
                    return (
                        <List.Item key={value.id}>
                            <PassengerItem name={value.name} type={"成人票"} id_type={"身份证"} id_num={value.identity}
                                           onDelete={async ()=>{
                                               await rmPassenger(value.id)
                                                   .catch(err=>{
                                                       Toast.show({
                                                           content: "失败！稍后重试"
                                                       })
                                                   });
                                               Toast.show({
                                                   content: "删除成功"
                                               });
                                               setItems(null);
                                           }}/>
                        </List.Item>
                    );
                });
                setItems(items);
            });
    }

    useEffect(()=>{
        if (!items){
            renderPassengers();
        }
    });

    return (
        <>
            <TitleNav title={"乘客信息"} backTo={"/me"}/>
            <Button block color={"success"} fill={"outline"} style={{letterSpacing: "1px", fontSize: "1rem"}}
                    onClick={()=>{
                        setVisible(true);
                    }}
            >
                <AddSquareOutline />{" "}添加乘客
            </Button>
            <List style={{marginTop: "2rem"}}>
                {items}
{/*                <List.Item>
                    <PassengerItem name={"李屹荣"} type={"成人票"} id_type={"身份证"} id_num={"xxxxxxxxxxxxxxxxx"} />
                </List.Item>*/}
            </List>
            <AddPassengerModal visible={visible} onFinish={()=> {
                setVisible(false);
                renderPassengers();
            }}/>
        </>
    );
}

export default PassengersPage;
